package chapter03;

public class BuildTree105 {
    /**
     * 前序pro[3,9,20,15,7] 中序in[9,3,15,20,7]
     * 根据前序第一个值start和start在中序位置划分左子树和右子树，中序左边值是左子树，中序右边值是右子树，递归左右子树
     * 前序pro[3,9,20,15,7] 中序in[9,3,15,20,7]
     *         -                    -
     *  process(preorder,preStart,preEnd,inorder,inStart,inEnd)
     *  利用前序preorder[preStart,preEnd]和中序inorder[inStart,inEnd]构建树
     *  递归出口
     *      1).preStart>preEnd
     *          return null
     *      2).生成子树
     *        cur=preorder[preStart]
     *        curNode=new TreeNode(cur) 生成当前节点
     *        index=0
     *         for i->(inStart,inEnd){
     *             if(inorder[i]==cur)
     *                 index=i  当前节点在中序数组中的下标
     *                 break
     *         curNode.left=process(preorder,preStart+1,preStart+index-inStart,inorder,inStart,index-1) 递归左子树
     *         curNode.right=process(preorder,preStart+index-inStart+1,preEnd,inorder,index+1,inEnd) 递归右子树
     *         return curNode 返回头节点
     */
    public class TreeNode {
       int val;
       TreeNode left;
       TreeNode right;
       TreeNode() {}
       TreeNode(int val) { this.val = val; }
       TreeNode(int val, TreeNode left, TreeNode right) {
           this.val = val;
           this.left = left;
           this.right = right;
       }
   }

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if(preorder.length==0){
            return null;
        }
        return process(preorder,0,preorder.length-1,inorder,0,inorder.length-1);
    }

    public TreeNode process(int[] preorder,int preStart,int preEnd, int[] inorder,int inStart,int inEnd){
        if(preStart>preEnd){
            return null;
        }
        int cur=preorder[preStart];
        TreeNode curNode=new TreeNode(cur);
        int index=0;
        for(int i=inStart;i<=inEnd;i++){
            if(inorder[i]==cur){
                index=i;
                break;
            }
        }
        curNode.left=process(preorder,preStart+1,preStart+index-inStart,inorder,inStart,index-1);
        curNode.right=process(preorder,preStart+index-inStart+1,preEnd,inorder,index+1,inEnd);
        return curNode;
    }
}
